import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/18 10:57
 * @description
 */
public class Solution2 {
    public static void main(String[] args) {

    }

    String SEP = ",";
    String NULL = "#";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        traverse(root, sb);
        return sb.toString();

    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        LinkedList<String> nodes = new LinkedList();
        for (String str : data.split(SEP)) {
            nodes.add(str);
        }
        return des(nodes);
    }

    public void traverse(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(NULL).append(SEP);
            return;
        }
        sb.append(String.valueOf(root.val)).append(SEP);
        traverse(root.left, sb);
        traverse(root.right, sb);

    }

    public TreeNode des(LinkedList<String> list) {
        if (list.isEmpty()) {
            return null;
        }
        String first = list.removeFirst();
        if (first.equals(NULL)) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(first));
        root.left = des(list);
        root.right = des(list);
        return root;
    }
}
